from flask import Flask, render_template_string, request, redirect, url_for, flash, session
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///grades.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


# 数据库模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    role = db.Column(db.String(20), default='teacher')  # 'teacher' or 'student'


class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    credits = db.Column(db.Float, nullable=False)  # 课程学分
    teacher_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    teacher = db.relationship('User', backref=db.backref('courses', lazy=True))


class Grade(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    student_name = db.Column(db.String(80), nullable=False)
    course_id = db.Column(db.Integer, db.ForeignKey('course.id'), nullable=False)
    course = db.relationship('Course', backref=db.backref('grades', lazy=True))
    daily_score = db.Column(db.Float, nullable=False)  # 平时成绩(30%)
    midterm_score = db.Column(db.Float, nullable=False)  # 期中成绩(20%)
    final_score = db.Column(db.Float, nullable=False)  # 期末成绩(50%)
    total_score = db.Column(db.Float, nullable=False)  # 总评成绩(自动计算)
    gpa = db.Column(db.Float)  # 绩点

    def calculate_total(self):
        # 计算总评成绩: 平时30% + 期中20% + 期末50%
        self.total_score = round(self.daily_score * 0.3 + self.midterm_score * 0.2 + self.final_score * 0.5, 2)
        self.calculate_gpa()

    def calculate_gpa(self):
        """计算绩点 (基于百分制成绩)"""
        if self.total_score >= 90:
            self.gpa = 4.0
        elif self.total_score >= 85:
            self.gpa = 3.7
        elif self.total_score >= 82:
            self.gpa = 3.3
        elif self.total_score >= 78:
            self.gpa = 3.0
        elif self.total_score >= 75:
            self.gpa = 2.7
        elif self.total_score >= 72:
            self.gpa = 2.3
        elif self.total_score >= 68:
            self.gpa = 2.0
        elif self.total_score >= 64:
            self.gpa = 1.5
        elif self.total_score >= 60:
            self.gpa = 1.0
        else:
            self.gpa = 0.0

    def is_passed(self):
        """判断是否及格"""
        return self.total_score >= 60


# 创建数据库表
with app.app_context():
    db.create_all()
    # 添加初始测试用户（仅第一次运行时需要）
    if not User.query.first():
        teacher = User(
            username='teacher',
            password=generate_password_hash('teacher123'),
            role='teacher'
        )
        student = User(
            username='student',
            password=generate_password_hash('student123'),
            role='student'
        )
        db.session.add(teacher)
        db.session.add(student)
        db.session.commit()


# 登录装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('请先登录', 'danger')
            return redirect(url_for('login'))
        return f(*args, **kwargs)

    return decorated_function


def teacher_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'role' not in session or session['role'] != 'teacher':
            flash('无权访问该页面', 'danger')
            return redirect(url_for('dashboard'))
        return f(*args, **kwargs)

    return decorated_function

# 基础模板
base_template = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩管理系统 - {% block title %}{% endblock %}</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            color: #333;
            background-color: #f5f5f5;
        }
        .container {
            width: 90%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        nav {
            background-color: #2c3e50;
            color: white;
            padding: 15px 0;
        }
        nav a {
            color: white;
            text-decoration: none;
            margin-right: 15px;
        }
        nav a:hover {
            text-decoration: underline;
        }
        .nav-links {
            float: right;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"],
        input[type="password"],
        input[type="number"],
        select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn {
            display: inline-block;
            background-color: #3498db;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
        }
        .btn:hover {
            background-color: #2980b9;
        }
        .btn-edit {
            background-color: #f39c12;
        }
        .btn-edit:hover {
            background-color: #e67e22;
        }
        .btn-delete {
            background-color: #e74c3c;
        }
        .btn-delete:hover {
            background-color: #c0392b;
        }
        .btn-cancel {
            background-color: #95a5a6;
        }
        .btn-cancel:hover {
            background-color: #7f8c8d;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #3498db;
            color: white;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .login-form, .register-form {
            max-width: 400px;
            margin: 50px auto;
            padding: 20px;
            background: white;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .alert {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .score-weights {
            margin: 20px 0;
            padding: 15px;
            background-color: #e8f4f8;
            border-radius: 5px;
        }
        .passed {
            color: green;
            font-weight: bold;
        }
        .failed {
            color: red;
            font-weight: bold;
        }
        .stats-summary {
            background-color: #e8f4f8;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <nav>
        <div class="container">
            <a href="{{ url_for('home') }}">成绩管理系统</a>
            <div class="nav-links">
                {% if 'user_id' in session %}
                    <span>欢迎, {{ session.username }} ({{ session.role }})</span>
                    {% if session.role == 'teacher' %}
                        <a href="{{ url_for('add_course') }}">添加课程</a>
                    {% endif %}
                    <a href="{{ url_for('view_grades') }}">查看成绩</a>
                    <a href="{{ url_for('logout') }}">退出</a>
                {% else %}
                    <a href="{{ url_for('login') }}">登录</a>
                    <a href="{{ url_for('register') }}">注册</a>
                {% endif %}
            </div>
        </div>
    </nav>

    <div class="container">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ category }}">{{ message }}</div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        {% block content %}{% endblock %}
    </div>
</body>
</html>
'''

def render_custom_template(template_content, **context):
    """自定义模板渲染函数"""
    full_template = base_template.replace('{% block content %}{% endblock %}',
                                          '{% block content %}' + template_content + '{% endblock %}')
    return render_template_string(full_template, **context)

# 路由
@app.route('/')
def home():
    if 'user_id' in session:
        return redirect(url_for('dashboard'))
    return redirect(url_for('login'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        user = User.query.filter_by(username=username).first()

        if user and check_password_hash(user.password, password):
            session['user_id'] = user.id
            session['username'] = user.username
            session['role'] = user.role
            flash('登录成功', 'success')
            return redirect(url_for('dashboard'))
        else:
            flash('用户名或密码错误', 'danger')

    login_template = '''
        <div class="login-form">
            <h2>登录</h2>
            <form method="POST">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <button type="submit" class="btn">登录</button>
            </form>
            <p>还没有账号？<a href="{{ url_for('register') }}">立即注册</a></p>
        </div>
    '''
    return render_custom_template(login_template)


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        role = request.form['role']

        if User.query.filter_by(username=username).first():
            flash('用户名已存在', 'danger')
            return redirect(url_for('register'))

        hashed_password = generate_password_hash(password)
        new_user = User(username=username, password=hashed_password, role=role)

        db.session.add(new_user)
        db.session.commit()

        flash('注册成功，请登录', 'success')
        return redirect(url_for('login'))

    register_template = '''
        <div class="register-form">
            <h2>注册</h2>
            <form method="POST">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <div class="form-group">
                    <label for="role">角色</label>
                    <select id="role" name="role" required>
                        <option value="teacher">教师</option>
                        <option value="student">学生</option>
                    </select>
                </div>
                <button type="submit" class="btn">注册</button>
            </form>
            <p>已有账号？<a href="{{ url_for('login') }}">立即登录</a></p>
        </div>
    '''
    return render_custom_template(register_template)


@app.route('/logout')
@login_required
def logout():
    session.clear()
    flash('您已成功退出', 'success')
    return redirect(url_for('login'))


@app.route('/dashboard')
@login_required
def dashboard():
    if session['role'] == 'teacher':
        courses = Course.query.filter_by(teacher_id=session['user_id']).all()
        grades = Grade.query.join(Course).filter(Course.teacher_id == session['user_id']).all()
    else:
        grades = Grade.query.filter_by(student_name=session['username']).all()
        courses = []

    # 计算学生平均绩点
    if session['role'] == 'student' and grades:
        total_credits = sum(grade.course.credits for grade in grades)
        weighted_gpa = sum(grade.gpa * grade.course.credits for grade in grades)
        avg_gpa = round(weighted_gpa / total_credits, 2) if total_credits > 0 else 0
    else:
        avg_gpa = None

    dashboard_template = '''
        <h2>欢迎来到成绩管理系统</h2>

        <div class="score-weights">
            <h4>成绩权重说明：</h4>
            <p>总评成绩 = 平时成绩(30%) + 期中成绩(20%) + 期末成绩(50%)</p>
            <p>及格线: 60分</p>
        </div>

        {% if session.role == 'teacher' %}
            <h3>您的课程</h3>
            {% if courses %}
                <table>
                    <thead>
                        <tr>
                            <th>课程名称</th>
                            <th>学分</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for course in courses %}
                            <tr>
                                <td>{{ course.name }}</td>
                                <td>{{ course.credits }}</td>
                                <td>
                                    <a href="{{ url_for('course_details', course_id=course.id) }}" class="btn">查看详情</a>
                                    <a href="{{ url_for('delete_course', course_id=course.id) }}" class="btn btn-delete" onclick="return confirm('确定删除这门课程及其所有成绩吗？')">删除</a>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            {% else %}
                <p>暂无课程</p>
            {% endif %}
            <a href="{{ url_for('add_course') }}" class="btn">添加新课程</a>

        {% else %}
            <h3>您的成绩</h3>
            {% if grades %}
                <p>平均绩点: {{ avg_gpa }}</p>
            {% endif %}
        {% endif %}
    '''
    return render_custom_template(dashboard_template, courses=courses, grades=grades, avg_gpa=avg_gpa)


@app.route('/course/<int:course_id>')
@login_required
def course_details(course_id):
    course = Course.query.get_or_404(course_id)

    if session['role'] == 'teacher' and course.teacher_id != session['user_id']:
        flash('无权访问此课程', 'danger')
        return redirect(url_for('dashboard'))

    grades = Grade.query.filter_by(course_id=course_id).all()

    # 如果是教师，确保只能看到自己课程的成绩
    if session['role'] == 'teacher':
        grades = [grade for grade in grades if grade.course.teacher_id == session['user_id']]

    # 计算统计信息
    stats = {
        'count': len(grades),
        'passed': sum(1 for g in grades if g.is_passed()),
        'failed': sum(1 for g in grades if not g.is_passed()),
        'avg_total': round(sum(g.total_score for g in grades) / len(grades), 2) if grades else 0,
        'avg_gpa': round(sum(g.gpa for g in grades) / len(grades), 2) if grades else 0,
        'highest': max(g.total_score for g in grades) if grades else 0,
        'lowest': min(g.total_score for g in grades) if grades else 0
    }

    course_template = '''
        <h2>{{ course.name }} 课程详情</h2>
        <p>学分: {{ course.credits }}</p>
        <p>授课教师: {{ course.teacher.username }}</p>

        <div class="stats-summary">
            <h3>统计概览</h3>
            <p>学生人数: {{ stats.count }}</p>
            <p>及格人数: {{ stats.passed }}</p>
            <p>不及格人数: {{ stats.failed }}</p>
            <p>平均分: {{ stats.avg_total }}</p>
            <p>平均绩点: {{ stats.avg_gpa }}</p>
            <p>最高分: {{ stats.highest }}</p>
            <p>最低分: {{ stats.lowest }}</p>
        </div>

        {% if session.role == 'teacher' %}
            <a href="{{ url_for('add_grade', course_id=course.id) }}" class="btn">添加成绩</a>
        {% endif %}

        <h3>成绩列表</h3>
        {% if grades %}
            <table>
                <thead>
                    <tr>
                        <th>学生姓名</th>
                        <th>平时成绩(30%)</th>
                        <th>期中成绩(20%)</th>
                        <th>期末成绩(50%)</th>
                        <th>总评成绩</th>
                        <th>绩点</th>
                        <th>状态</th>
                        {% if session.role == 'teacher' %}
                            <th>操作</th>
                        {% endif %}
                    </tr>
                </thead>
                <tbody>
                    {% for grade in grades %}
                        <tr>
                            <td>{{ grade.student_name }}</td>
                            <td>{{ grade.daily_score }}</td>
                            <td>{{ grade.midterm_score }}</td>
                            <td>{{ grade.final_score }}</td>
                            <td>{{ grade.total_score }}</td>
                            <td>{{ grade.gpa }}</td>
                            <td>
                                {% if grade.is_passed() %}
                                    <span class="passed">及格</span>
                                {% else %}
                                    <span class="failed">不及格</span>
                                {% endif %}
                            </td>
                            {% if session.role == 'teacher' %}
                                <td>
                                    <a href="{{ url_for('edit_grade', grade_id=grade.id) }}" class="btn btn-edit">编辑</a>
                                    <a href="{{ url_for('delete_grade', grade_id=grade.id) }}" class="btn btn-delete" onclick="return confirm('确定删除吗？')">删除</a>
                                </td>
                            {% endif %}
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        {% else %}
            <p>暂无成绩记录</p>
        {% endif %}

        <a href="{{ url_for('dashboard') }}" class="btn">返回</a>
    '''
    return render_custom_template(course_template, course=course, grades=grades, stats=stats)


@app.route('/add_course', methods=['GET', 'POST'])
@login_required
@teacher_required
def add_course():
    if request.method == 'POST':
        name = request.form['name']
        credits = float(request.form['credits'])

        if Course.query.filter_by(name=name).first():
            flash('课程已存在', 'danger')
            return redirect(url_for('add_course'))

        new_course = Course(
            name=name,
            credits=credits,
            teacher_id=session['user_id']
        )

        db.session.add(new_course)
        db.session.commit()

        flash('课程添加成功', 'success')
        return redirect(url_for('dashboard'))

    add_course_template = '''
        <h2>添加课程</h2>
        <form method="POST">
            <div class="form-group">
                <label for="name">课程名称</label>
                <input type="text" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label for="credits">学分</label>
                <input type="number" id="credits" name="credits" step="0.5" min="0.5" max="10" required>
            </div>
            <button type="submit" class="btn">添加</button>
            <a href="{{ url_for('dashboard') }}" class="btn btn-cancel">取消</a>
        </form>
    '''
    return render_custom_template(add_course_template)


@app.route('/add_grade/<int:course_id>', methods=['GET', 'POST'])
@login_required
@teacher_required
def add_grade(course_id):
    course = Course.query.get_or_404(course_id)

    if course.teacher_id != session['user_id']:
        flash('无权为此课程添加成绩', 'danger')
        return redirect(url_for('dashboard'))

    if request.method == 'POST':
        student_name = request.form['student_name']
        daily_score = float(request.form['daily_score'])
        midterm_score = float(request.form['midterm_score'])
        final_score = float(request.form['final_score'])

        new_grade = Grade(
            student_name=student_name,
            course_id=course_id,
            daily_score=daily_score,
            midterm_score=midterm_score,
            final_score=final_score,
            total_score=0.0  # 初始值，calculate_total会计算正确值
        )
        new_grade.calculate_total()  # 计算总评成绩和绩点

        db.session.add(new_grade)
        db.session.commit()

        flash('成绩添加成功', 'success')
        return redirect(url_for('course_details', course_id=course_id))

    add_grade_template = '''
        <h2>为 {{ course.name }} 添加成绩</h2>
        <p>学分: {{ course.credits }}</p>
        <form method="POST">
            <div class="form-group">
                <label for="student_name">学生姓名</label>
                <input type="text" id="student_name" name="student_name" required>
            </div>
            <div class="form-group">
                <label for="daily_score">平时成绩(30%)</label>
                <input type="number" id="daily_score" name="daily_score" step="0.1" min="0" max="100" required>
            </div>
            <div class="form-group">
                <label for="midterm_score">期中成绩(20%)</label>
                <input type="number" id="midterm_score" name="midterm_score" step="0.1" min="0" max="100" required>
            </div>
            <div class="form-group">
                <label for="final_score">期末成绩(50%)</label>
                <input type="number" id="final_score" name="final_score" step="0.1" min="0" max="100" required>
            </div>
            <button type="submit" class="btn">添加</button>
            <a href="{{ url_for('course_details', course_id=course.id) }}" class="btn btn-cancel">取消</a>
        </form>
    '''
    return render_custom_template(add_grade_template, course=course)


@app.route('/edit_grade/<int:grade_id>', methods=['GET', 'POST'])
@login_required
@teacher_required
def edit_grade(grade_id):
    grade = Grade.query.get_or_404(grade_id)
    course = grade.course

    if course.teacher_id != session['user_id']:
        flash('无权编辑此成绩', 'danger')
        return redirect(url_for('dashboard'))

    if request.method == 'POST':
        grade.student_name = request.form['student_name']
        grade.daily_score = float(request.form['daily_score'])
        grade.midterm_score = float(request.form['midterm_score'])
        grade.final_score = float(request.form['final_score'])
        grade.calculate_total()  # 重新计算总评成绩和绩点

        db.session.commit()
        flash('成绩更新成功', 'success')
        return redirect(url_for('course_details', course_id=course.id))

    edit_grade_template = '''
        <h2>编辑成绩 - {{ grade.course.name }}</h2>
        <form method="POST">
            <div class="form-group">
                <label for="student_name">学生姓名</label>
                <input type="text" id="student_name" name="student_name" value="{{ grade.student_name }}" required>
            </div>
            <div class="form-group">
                <label for="daily_score">平时成绩(30%)</label>
                <input type="number" id="daily_score" name="daily_score" step="0.1" min="0" max="100" value="{{ grade.daily_score }}" required>
            </div>
            <div class="form-group">
                <label for="midterm_score">期中成绩(20%)</label>
                <input type="number" id="midterm_score" name="midterm_score" step="0.1" min="0" max="100" value="{{ grade.midterm_score }}" required>
            </div>
            <div class="form-group">
                <label for="final_score">期末成绩(50%)</label>
                <input type="number" id="final_score" name="final_score" step="0.1" min="0" max="100" value="{{ grade.final_score }}" required>
            </div>
            <button type="submit" class="btn">更新</button>
            <a href="{{ url_for('course_details', course_id=course.id) }}" class="btn btn-cancel">取消</a>
        </form>
    '''
    return render_custom_template(edit_grade_template, grade=grade, course=course)


@app.route('/delete_grade/<int:grade_id>')
@login_required
@teacher_required
def delete_grade(grade_id):
    grade = Grade.query.get_or_404(grade_id)
    course = grade.course

    if course.teacher_id != session['user_id']:
        flash('无权删除此成绩', 'danger')
        return redirect(url_for('dashboard'))

    db.session.delete(grade)
    db.session.commit()
    flash('成绩删除成功', 'success')
    return redirect(url_for('course_details', course_id=course.id))


@app.route('/delete_course/<int:course_id>')
@login_required
@teacher_required
def delete_course(course_id):
    course = Course.query.get_or_404(course_id)

    if course.teacher_id != session['user_id']:
        flash('无权删除此课程', 'danger')
        return redirect(url_for('dashboard'))

    # 先删除关联的成绩记录
    Grade.query.filter_by(course_id=course_id).delete()
    db.session.delete(course)
    db.session.commit()

    flash('课程及关联成绩已删除', 'success')
    return redirect(url_for('dashboard'))


@app.route('/view_grades')
@login_required
def view_grades():
    if session['role'] == 'teacher':
        grades = Grade.query.join(Course).filter(Course.teacher_id == session['user_id']).all()
    else:
        grades = Grade.query.filter_by(student_name=session['username']).all()

    # 计算学生平均绩点
    if session['role'] == 'student' and grades:
        total_credits = sum(grade.course.credits for grade in grades)
        weighted_gpa = sum(grade.gpa * grade.course.credits for grade in grades)
        avg_gpa = round(weighted_gpa / total_credits, 2) if total_credits > 0 else 0
    else:
        avg_gpa = None

    view_grades_template = '''
        <h2>成绩列表</h2>

        <div class="score-weights">
            <h4>成绩权重说明：</h4>
            <p>总评成绩 = 平时成绩(30%) + 期中成绩(20%) + 期末成绩(50%)</p>
            <p>及格线: 60分</p>
        </div>

        {% if session.role == 'student' and avg_gpa is not none %}
            <p>平均绩点: {{ avg_gpa }}</p>
        {% endif %}

        {% if grades %}
            <table>
                <thead>
                    <tr>
                        <th>课程</th>
                        <th>学分</th>
                        <th>授课教师</th>
                        <th>平时成绩(30%)</th>
                        <th>期中成绩(20%)</th>
                        <th>期末成绩(50%)</th>
                        <th>总评成绩</th>
                        <th>绩点</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
                    {% for grade in grades %}
                        <tr>
                            <td>{{ grade.course.name }}</td>
                            <td>{{ grade.course.credits }}</td>
                            <td>{{ grade.course.teacher.username }}</td>
                            <td>{{ grade.daily_score }}</td>
                            <td>{{ grade.midterm_score }}</td>
                            <td>{{ grade.final_score }}</td>
                            <td>{{ grade.total_score }}</td>
                            <td>{{ grade.gpa }}</td>
                            <td>
                                {% if grade.is_passed() %}
                                    <span class="passed">及格</span>
                                {% else %}
                                    <span class="failed">不及格</span>
                                {% endif %}
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        {% else %}
            <p>暂无成绩记录</p>
        {% endif %}
    '''
    return render_custom_template(view_grades_template, grades=grades, avg_gpa=avg_gpa)


if __name__ == '__main__':
    app.run(debug=True, port=5001)